import { Injectable, Logger } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { SecurityEventType, SecurityLevel } from '../entities/security-log.entity';

export interface SecurityEventPayload {
  eventType: SecurityEventType;
  securityLevel: SecurityLevel;
  eventTitle: string;
  eventDescription: string;
  userId?: string;
  username?: string;
  ipAddress?: string;
  requestUrl?: string;
  requestMethod?: string;
  userAgent?: string;
  additionalInfo?: any;
  errorMessage?: string;
  stackTrace?: string;
}

@Injectable()
export class SecurityEventEmitter {
  private readonly logger = new Logger(SecurityEventEmitter.name);

  constructor(private readonly eventEmitter: EventEmitter2) {}

  /**
   * 发射安全事件
   */
  emit(eventName: string, payload: SecurityEventPayload) {
    try {
      this.eventEmitter.emit(eventName, payload);
      this.logger.debug(`安全事件已发射: ${eventName} - ${payload.eventTitle}`);
    } catch (error) {
      this.logger.error(`发射安全事件失败: ${error.message}`, error.stack);
    }
  }

  /**
   * 发射认证成功事件
   */
  emitAuthSuccess(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.auth.success', {
      ...payload,
      eventType: SecurityEventType.AUTH_SUCCESS,
      securityLevel: SecurityLevel.LOW,
    });
  }

  /**
   * 发射认证失败事件
   */
  emitAuthFailed(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.auth.failed', {
      ...payload,
      eventType: SecurityEventType.AUTH_FAILED,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射未授权访问事件
   */
  emitUnauthorizedAccess(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.unauthorized.access', {
      ...payload,
      eventType: SecurityEventType.UNAUTHORIZED_ACCESS,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射权限拒绝事件
   */
  emitPermissionDenied(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.permission.denied', {
      ...payload,
      eventType: SecurityEventType.PERMISSION_DENIED,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射验证错误事件
   */
  emitValidationError(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.validation.error', {
      ...payload,
      eventType: SecurityEventType.VALIDATION_ERROR,
      securityLevel: SecurityLevel.MEDIUM,
    });
  }

  /**
   * 发射业务错误事件
   */
  emitBusinessError(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.business.error', {
      ...payload,
      eventType: SecurityEventType.BUSINESS_ERROR,
      securityLevel: SecurityLevel.MEDIUM,
    });
  }

  /**
   * 发射系统错误事件
   */
  emitSystemError(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.system.error', {
      ...payload,
      eventType: SecurityEventType.SYSTEM_ERROR,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射可疑活动事件
   */
  emitSuspiciousActivity(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.suspicious.activity', {
      ...payload,
      eventType: SecurityEventType.SUSPICIOUS_ACTIVITY,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射频率限制事件
   */
  emitRateLimitExceeded(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.rate.limit.exceeded', {
      ...payload,
      eventType: SecurityEventType.RATE_LIMIT_EXCEEDED,
      securityLevel: SecurityLevel.HIGH,
    });
  }

  /**
   * 发射SQL注入尝试事件
   */
  emitSqlInjectionAttempt(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.sql.injection.attempt', {
      ...payload,
      eventType: SecurityEventType.SQL_INJECTION_ATTEMPT,
      securityLevel: SecurityLevel.CRITICAL,
    });
  }

  /**
   * 发射XSS尝试事件
   */
  emitXssAttempt(payload: Omit<SecurityEventPayload, 'eventType' | 'securityLevel'>) {
    this.emit('security.xss.attempt', {
      ...payload,
      eventType: SecurityEventType.XSS_ATTEMPT,
      securityLevel: SecurityLevel.CRITICAL,
    });
  }

  /**
   * 发射自定义安全事件
   */
  emitCustomEvent(payload: SecurityEventPayload) {
    this.emit('security.custom.event', payload);
  }
}
